/**
 *
 * @author Patricia Blanco created 2013 copyright 2013
 */
package dieci.database.order;

import dieci.database.PersistentObject;
import dieci.database.SessionFactoryUtil;
import dieci.hibernate.HibOrderDetails;
import dieci.hibernate.HibOrder;
import dieci.managers.supplier.SupplierManager;
import dieci.system.Order;
import dieci.system.OrderDetails;
import dieci.system.Supplier;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import org.hibernate.Session;
import java.util.logging.Logger;
import org.hibernate.criterion.Restrictions;

public class OrderHibernateDAO implements OrderDAO
{

    private static Logger logger = Logger.getLogger("OrderDAO.log");
    private SupplierManager supplierManager = new SupplierManager();
    
    @Override
    public List<Order> list()
    {
        List<Order> orders = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibOrder> hibOrders = session.createCriteria(HibOrder.class).list();
            for (HibOrder dbOrder : hibOrders) {
                Set<OrderDetails> details = new HashSet<>();
                for (HibOrderDetails hibOrderDetails : dbOrder.getDetails()) {
                    details.add(new OrderDetails(hibOrderDetails.getId().getProductId(),
                            hibOrderDetails.getAmount(), hibOrderDetails.getCost()));
                }
                Supplier supplier = supplierManager.findById(dbOrder.getSupplierId());
                Order order = new Order(supplier, dbOrder.getOrderDate(), details,dbOrder.getTotalOrderAmount());
                order.setOrderId(dbOrder.getOrderId());
                orders.add(order);
            }

            return orders;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando", e.getMessage());

            throw new IllegalStateException("Error al listar", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public Order findByOrderId(long id)
    {
        Order result = null;
        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            HibOrder hibOrder = (HibOrder) session.createCriteria(HibOrder.class).add(Restrictions.eq("orderId", id)).uniqueResult();
            if (hibOrder != null) {
                Set<OrderDetails> details = new HashSet<>();
                for (HibOrderDetails detail : hibOrder.getDetails()) {

                    OrderDetails p = new OrderDetails(detail.getId().getProductId(), detail.getAmount(), detail.getCost());
                    p.setOrderId(detail.getId().getOrderId());
                    details.add(p);
                }
                Supplier supplier = supplierManager.findById(hibOrder.getSupplierId());
                result = new Order(supplier,
                        hibOrder.getOrderDate(), details, hibOrder.getTotalOrderAmount());
                result.setOrderId(hibOrder.getOrderId());
            }

        }
        catch (Exception e) {
            throw new IllegalStateException("Error al buscar por articulo", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }

        return result;
    }

    @Override
    public void delete(PersistentObject object)
    {
        Session session = null;

        Order order = (Order) object;
        Order found = findByOrderId(order.getOrderId());
        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();

            session.beginTransaction();

            if (found != null) {
                //DELETE
                order.setOrderId(found.getOrderId());

                Set<HibOrderDetails> hibOrderDetailss = new HashSet<>();
                for (OrderDetails detail : order.getDetails()) {
                    HibOrderDetails p = new HibOrderDetails(detail, order.getOrderId());
                    hibOrderDetailss.add(p);
                }
                HibOrder hibOrder = new HibOrder(order.getOrderId(), (Order) order);
                hibOrder.setDetails(hibOrderDetailss);
                session.delete(hibOrder);

            }

            session.getTransaction().commit();

        }
        catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw new IllegalStateException("Error al eliminar", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public void saveOrUpdate(PersistentObject object)
    {
        Session session = null;

        Order order = (Order) object;
        Order found = null;

        if (order.getOrderId() > 0) {
            found = findByOrderId(order.getOrderId());
        }

        try {
            session = SessionFactoryUtil.getInstance().getCurrentSession();

            session.beginTransaction();

            if (found != null) {
                //UPDATE
                order.setOrderId(found.getOrderId());

                Set<HibOrderDetails> hibOrderDetailss = new HashSet<>();
                for (OrderDetails detail : order.getDetails()) {
                    HibOrderDetails d = new HibOrderDetails(detail, order.getOrderId());
                    hibOrderDetailss.add(d);
                }
                HibOrder hibOrder = new HibOrder(order.getOrderId(), (Order) order);
                hibOrder.setDetails(hibOrderDetailss);
                session.saveOrUpdate(hibOrder);

            }
            else {
                //NEW
                HibOrder hibOrder = new HibOrder(order);

                // generate new id for the orderuct
                session.save(hibOrder);
                // add the details
                for (OrderDetails detail : order.getDetails()) {
                    hibOrder.getDetails().add(
                            new HibOrderDetails(detail, hibOrder.getOrderId()));
                }

                // If the enty already exist update it.
                session.saveOrUpdate(hibOrder);
            }

            session.getTransaction().commit();

        }
        catch (Exception e) {
            if (session != null) {
                session.getTransaction().rollback();
            }
            throw new IllegalStateException("Error al guardar o actualizar", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public List<Order> findByOrderDateRange(Date start, Date end)
    {
        List<Order> orders = new ArrayList<>();

        Session session = SessionFactoryUtil.getInstance().getCurrentSession();
        try {
            session.beginTransaction();

            List<HibOrder> hibOrders = session.createCriteria(HibOrder.class).add(Restrictions.between("orderDate", start, end)).list();
            for (HibOrder dbOrder : hibOrders) {
                Set<OrderDetails> details = new HashSet<>();
                for (HibOrderDetails hibOrderDetails : dbOrder.getDetails()) {
                    details.add(new OrderDetails(hibOrderDetails.getId().getProductId(),
                            hibOrderDetails.getAmount(), hibOrderDetails.getCost()));
                }
                Supplier supplier = supplierManager.findById(dbOrder.getSupplierId());
                Order order = new Order(supplier, dbOrder.getOrderDate(), details, dbOrder.getTotalOrderAmount());
                order.setOrderId(dbOrder.getOrderId());
                orders.add(order);
            }

            return orders;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando compras por fecha", e.getMessage());

            throw new IllegalStateException("Error al listar", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }
    }

    @Override
    public List<Order> findBySupplierName(String supplierName)
    {
        List<Order> orders = new ArrayList<>();

        Session session = null;
        
        try 
        {
            List<Supplier> suppliers = new SupplierManager().find(supplierName);

            session = SessionFactoryUtil.getInstance().getCurrentSession();
            session.beginTransaction();
            
            for (Supplier supplier : suppliers) {
                List<HibOrder> hibOrders = session.createCriteria(HibOrder.class).add(Restrictions.like("supplierId", supplier.getSupplierId())).list();
                for (HibOrder dbOrder : hibOrders) {
                    Set<OrderDetails> details = new HashSet<>();
                    for (HibOrderDetails hibOrderDetails : dbOrder.getDetails()) {
                        details.add(new OrderDetails(hibOrderDetails.getId().getProductId(),
                                hibOrderDetails.getAmount(), hibOrderDetails.getCost()));
                    }
                    Order order = new Order(supplier, dbOrder.getOrderDate(), details,
                            dbOrder.getTotalOrderAmount());
                    order.setOrderId(dbOrder.getOrderId());
                    orders.add(order);
                }
            }


            return orders;
        }
        catch (Exception e) {

            logger.log(Level.INFO, "Error listando compras para el proveedor " + supplierName, e.getMessage());

            throw new IllegalStateException("Error al listar", e);
        }
        finally {
            if (session != null && session.isOpen()) {

                session.close();
            }
        }
    }
}
